package com.wh.wisdomsite.xbox.server;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.wh.wisdomsite.xbox.ba.service.IAppSecretService;
import com.wh.wisdomsite.xbox.pojo.ba.AppSecretIn;
import com.wh.wisdomsite.xbox.pojo.ba.AppSecretModifySecretIn;
import com.wh.wisdomsite.xbox.common.Constants;
import com.wh.wisdomsite.xbox.common.reponse.CommonResult;
import com.wh.wisdomsite.xbox.ba.entity.AppSecret;

import com.wh.wisdomsite.xbox.common.util.ResManager;
import com.wh.wisdomsite.xbox.utils.encrypt.md5.MD5Tool_Two;
import com.wh.wisdomsite.xbox.server.listener.SessionListener;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.wh.wisdomsite.xbox.utils.SecCode;
import com.wh.wisdomsite.xbox.utils.json.JsonUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.bind.annotation.RequestMethod;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 应用服务端登录Controller
 * @Package com.wh.wisdomsite.xbox.server
 * @author 谢泽鹏
 * @date 2014年10月8日 下午4:02:14
 * @Copyright 个人版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2014
 * @version V1.0
 */
@Controller
@RequestMapping("/server")
public class AdminLoginController {

    private static final Log logger = LogFactory.getLog(AdminLoginController.class);

    @Autowired
    private IAppSecretService iAppSecretService;

    /**
     * 生成验证码
     * @param response
     */
    @RequestMapping(value = "/generatCode.do", method = RequestMethod.GET)
    public void generatCode(HttpServletResponse response, HttpServletRequest request) {
        try {
            logger.info("管理员登录-->>generatCode-->>开始");
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            //生成验证码
            String code = SecCode.drawImg(output);
            logger.info("管理员登录-->>generatCode-->> : " + code);
            request.getSession().setAttribute(Constants.SERVER_ADMIN_VALICODE, code);
            //将获取的验证码信息返回到页面
            ServletOutputStream out = response.getOutputStream();
            output.writeTo(out);
            output.flush();
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("管理员登录-->>异常 Exception" + e.getMessage());
        }
            logger.info("管理员登录-->>generatCode-->>结束");
    }

    /**
     * 登录方法
     * @param response
     * @param appSecretIn
     */
    @RequestMapping(value = "/login.do", method = RequestMethod.POST)
    public void login(HttpServletResponse response, HttpServletRequest request, AppSecretIn appSecretIn){
        CommonResult commonResult = new CommonResult();
        try{
            logger.info("管理员登录-->>开始");
            //账户判断
            if(StringUtils.isEmpty(appSecretIn.getAppKey())){
                commonResult.setCode(Constants.CODE_FAIL);
                commonResult.setMessage("登录账户不能为空");
                ResManager.getJsonOut(response).print(JsonUtil.Json2All(commonResult));
                return;
            }
            //账户密码
            if(StringUtils.isEmpty(appSecretIn.getSecret())){
                commonResult.setCode(Constants.CODE_FAIL);
                commonResult.setMessage("账户密码不能为空");
                ResManager.getJsonOut(response).print(JsonUtil.Json2All(commonResult));
                return;
            }
            //验证码空判断
            if(StringUtils.isEmpty(appSecretIn.getValicode())){
                commonResult.setCode(Constants.CODE_FAIL);
                commonResult.setMessage("验证码不能为空");
                ResManager.getJsonOut(response).print(JsonUtil.Json2All(commonResult));
                return;
            }
            HttpSession session = request.getSession(true);
            String code = session.getAttribute(Constants.SERVER_ADMIN_VALICODE).toString();
            //判断验证码是否正确
            if(!appSecretIn.getValicode().equalsIgnoreCase(code)){
                commonResult.setCode(Constants.CODE_FAIL);
                commonResult.setMessage("验证码不正确");
                ResManager.getJsonOut(response).print(JsonUtil.Json2All(commonResult));
                return;
            }
            EntityWrapper<AppSecret> ew = new EntityWrapper<AppSecret>();
            ew.setEntity(new AppSecret());
            ew.eq("T_APP_KEY", appSecretIn.getAppKey());

            //获取秘钥
            AppSecret appSecret = iAppSecretService.selectOne(ew);
            appSecretIn.setSecret(MD5Tool_Two.MD5(appSecretIn.getSecret()));
            if((null == appSecret) || (!appSecret.getSecret().equals(appSecretIn.getSecret()))){
                commonResult.setCode(Constants.CODE_FAIL);
                commonResult.setMessage("账户或密码错误");
                ResManager.getJsonOut(response).print(JsonUtil.Json2All(commonResult));
                return;
            }

            //处理用户登录(保持同一时间同一账号只能在一处登录)使用 同步方法，只允许一个线程进入，才好验证是否重复登录
            if(SessionListener.checkHasLogin(appSecret)){
                SessionListener.removeSessionUser(appSecret.getId(), session.getId());
                if(null == request.getSession(false)){
                    logger.info("管理员登录-->>checkHasLogin-->>您的账号已经在另一处登录了,你被迫下线!");
                }
            }
            //设置会话时长30分钟
            session.setMaxInactiveInterval(30 * 60);
            //将appSecret对象放入session
            session.setAttribute(Constants.SERVER_ADMIN_APPSECRET, appSecret);
            session.setAttribute("sysName", "Xbox数据插件系统v2.0版本");
            session.setAttribute("loginStyle", "default");
            SessionListener.addUserSession(session);

            commonResult.setCode(Constants.CODE_SUCCESS);
            commonResult.setMessage("登录成功");
            ResManager.getJsonOut(response).print(JsonUtil.Json2All(commonResult));
            logger.info("管理员登录-->>结束");
        }catch(Exception e){
            e.printStackTrace();
            logger.error("管理员登录-->>异常 Exception" + e.getMessage());
        }
    }


    /**
     * 跳转到框架页面
     */
    @RequestMapping(value = "/main.do", method = RequestMethod.GET)
    public String main() {
        return "main/main";
    }

    /**
     * 跳转到首页页面
     * @return
     */
    @RequestMapping(value = "/index.do", method = RequestMethod.GET)
    public String index() {
        return "index";
    }


    /**
     * 修改密码
     * @param response
     * @param request
     * @param appSecretModifyIn
     */
    @RequestMapping(value = "/modify.do", method = RequestMethod.POST)
    public void modify(HttpServletResponse response, HttpServletRequest request, AppSecretModifySecretIn appSecretModifyIn){
        CommonResult commonResult = new CommonResult();
        try {
            HttpSession session = request.getSession(true);
            String appKey = ((AppSecret)session.getAttribute(Constants.SERVER_ADMIN_APPSECRET)).getAppKey();
            logger.info("修改密码-->>开始");
            //判断密码是否为空
            if(StringUtils.isEmpty(appSecretModifyIn.getSecret()) || StringUtils.isEmpty(appSecretModifyIn.getNewSecret()) || StringUtils.isEmpty(appSecretModifyIn.getConfirmNewSecret())){
                commonResult.setCode(Constants.CODE_FAIL);
                commonResult.setMessage("新/旧密码不能为空");
                ResManager.getJsonOut(response).print(JsonUtil.Json2All(commonResult));
                return;
            }
            if(!appSecretModifyIn.getNewSecret().equals(appSecretModifyIn.getConfirmNewSecret())){
                commonResult.setCode(Constants.CODE_FAIL);
                commonResult.setMessage("两次密码不一致");
                ResManager.getJsonOut(response).print(JsonUtil.Json2All(commonResult));
                return;
            }
            EntityWrapper<AppSecret> ewAppSecret = new EntityWrapper<AppSecret>();
            ewAppSecret.setEntity(new AppSecret());
            ewAppSecret.eq("T_APP_KEY", appKey);

            //获取秘钥
            AppSecret appSecret_ = iAppSecretService.selectOne(ewAppSecret);
            appSecretModifyIn.setSecret(MD5Tool_Two.MD5(appSecretModifyIn.getSecret()));
            //验证旧密码是否正确
            if(appSecret_ == null || (!appSecret_.getSecret().equals(appSecretModifyIn.getSecret()))){
                commonResult.setCode(Constants.CODE_FAIL);
                commonResult.setMessage("旧密码错误");
                ResManager.getJsonOut(response).print(JsonUtil.Json2All(commonResult));
                return;
            }else {
                //给新密码加密
                appSecretModifyIn.setNewSecret(MD5Tool_Two.MD5(appSecretModifyIn.getNewSecret()));
                appSecretModifyIn.setAppKey(appKey);

                AppSecret appSecret = new AppSecret();
                appSecret.setSecret(MD5Tool_Two.MD5(appSecretModifyIn.getNewSecret()));

                EntityWrapper<AppSecret> ew = new EntityWrapper<AppSecret>();
                ew.setEntity(new AppSecret());
                ew.eq("T_APP_KEY", appKey);

                iAppSecretService.update(appSecret, ew);
                commonResult.setCode(Constants.CODE_SUCCESS);
                commonResult.setMessage("账户密码修改成功");
                ResManager.getJsonOut(response).print(JsonUtil.Json2All(commonResult));
            }
            logger.info("管理员登录-->>结束");
        } catch (Exception e){
            e.printStackTrace();
            logger.error("修改密码-->>异常 Exception" + e.getMessage());
        }
    }


    /**
     * 退出登录
     * @param response
     * @param request
     */
    @RequestMapping("logout")
    public void logout(HttpServletResponse response, HttpServletRequest request) {
        logger.info("退出登录-->>开始");
        Map<String, Object> map = new HashMap<String, Object>();
        try{
            HttpSession session = request.getSession(true);
            Object objSession = session.getAttribute(Constants.SERVER_ADMIN_APPSECRET);
            if (null != objSession) {
                AppSecret appSecret = (AppSecret) objSession;
                if (null != appSecret && null != appSecret.getId()) {
                    SessionListener.removeLoginOutuser(appSecret.getId(), session.getId());
                }
            }
            map.put("code", Constants.CODE_SUCCESS);
            map.put("message", "退出应用系统成功！");
        } catch (Exception e){
            e.printStackTrace();
            map.put("code", Constants.CODE_FAIL);
            map.put("message", "退出应用系统失败！");
            logger.error("修改密码-->>异常 Exception" + e.getMessage());
        }
            ResManager.getJsonOut(response).print(JsonUtil.Json2All(map));

    }


}
